package heap

import (
	. "jvm/typedef"
)

// 创建数组对象
func (self *Class) NewArray(length U4) *Object {
	if !self.IsArray() {
		panic("Not array class: " + self.name)
	}
	switch self.name {
	case "[Z":
		return &Object{class: self, data: make([]I1, length)}
	case "[B":
		return &Object{class: self, data: make([]I1, length)}
	case "[S":
		return &Object{class: self, data: make([]I2, length)}
	case "[C":
		return &Object{class: self, data: make([]U2, length)}
	case "[I":
		return &Object{class: self, data: make([]I4, length)}
	case "[J":
		return &Object{class: self, data: make([]I8, length)}
	case "[F":
		return &Object{class: self, data: make([]F4, length)}
	case "[D":
		return &Object{class: self, data: make([]F8, length)}
	default:
		return &Object{class: self, data: make([]*Object, length)}
	}
}
func (self *Class) IsArray() bool {
	return self.name[0] == '['
}
func (self *Class) ElementClass() *Class {
	name := getElementName(self.name)
	return self.loader.LoadClass(name)
}

// 获取数组内元素的类名
func getElementName(name string) string {
	if name[0] == '[' {
		elementName := name[1:]
		if elementName[0] == '[' {
			return elementName
		}
		// if elementName[0] == 'L' {
		// 	return elementName[1 : len(elementName)-1]
		// }
		// for className, d := range primitiveTypes {
		// 	if d == elementName {
		// 		// primitive
		// 		return className
		// 	}
		// }
		panic("Invalid descriptor: " + name)
	}
	panic("Not array: " + name)
}

// var primitiveTypes = map[string]string{
// 	"void":    "V",
// 	"boolean": "Z",
// 	"byte":    "B",
// 	"short":   "S",
// 	"int":     "I",
// 	"long":    "J",
// 	"char":    "C",
// 	"float":   "F",
// 	"double":  "D",
// }
